<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use Auth;

class OrdersController extends Controller
{
    public function store(Request $request, User $user)
    {
        $user  = $request->user();

        //充值订单
        if($request->recharge)
        {

            // 开启一个数据库事务
            $order = \DB::transaction(function () use ($user, $request) {

                $recharge_detail = \DB::table('recharge_package')->where('id', $request->recharge_package_id)->first();

                if($recharge_detail->money_tax && $recharge_detail->money_tax != 0) {
                    $recharge_money = $recharge_detail->money_tax;
                } else {
                    $recharge_money = $recharge_detail->money;
                }

                // 创建一个订单
                $order = new Order([
                    'total_amount' => $recharge_money,
                    'recharge_package_id' => $recharge_detail->id,
                    'status' => 1, //1是话费充值订单类型
                    'cellphone' => $request->cellphone,
                    'credit_num' => $request->credit_num,
                    'recharge_type' => $request->recharge_type,
                    'is_aop' => $request->is_AOP,
                    'exchange_rate' => number_format(get_exchange_rate (), 2)
                ]);
                // 订单关联到当前用户
                $order->user()->associate($user);
                // 写入数据库
                $order->save();

                return redirect()->route('payment.wechat', ['order' => $order]);
            });

            return $order;
        }
    }

    public function rechargeRecord(Request $request)
    {
        $recharge_records = Order::where('user_id', Auth::id())->orderBy('updated_at', 'desc')->paginate(10);

        if ($request->ajax()) {
            $view = view('mobile.layouts._recharge-record-item',compact('recharge_records'))->render();
            return response()->json(['html'=>$view]);
        }

        return view(isMobile() . 'mobile_recharge.record', compact('recharge_records'));
    }

    public function rechargeRecordDetail(Order $order)
    {
        $this->authorize('own', $order);

        return view(isMobile() . 'mobile_recharge.record_detail', compact('order'));
    }
}
